<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  

  
  <title>shiro授权 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="授权授权，也叫访问控制，即在应用中控制谁能访问哪些资源（如访问页面/编辑数据/页面操作等）。在授权中需了解的几个关键对象：主体（Subject）、资源（Resource）、权限（Permission）、角色（Role）。">
<meta name="keywords" content="shiro">
<meta property="og:type" content="article">
<meta property="og:title" content="shiro授权">
<meta property="og:url" content="http://yoursite.com/2018/10/12/2018-03-13-shiro授权/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="授权授权，也叫访问控制，即在应用中控制谁能访问哪些资源（如访问页面/编辑数据/页面操作等）。在授权中需了解的几个关键对象：主体（Subject）、资源（Resource）、权限（Permission）、角色（Role）。">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/6.png">
<meta property="og:updated_time" content="2018-11-01T14:24:04.928Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shiro授权">
<meta name="twitter:description" content="授权授权，也叫访问控制，即在应用中控制谁能访问哪些资源（如访问页面/编辑数据/页面操作等）。在授权中需了解的几个关键对象：主体（Subject）、资源（Resource）、权限（Permission）、角色（Role）。">
<meta name="twitter:image" content="http://p1aoqp63y.bkt.clouddn.com/6.png">
  
    <link rel="alternate" href="/org/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/org/css/style.css">
</head>
</html>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/org/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/org/">Home</a>
        
          <a class="main-nav-link" href="/org/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/org/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-2018-03-13-shiro授权" class="article article-type-post" itemscope="" itemprop="blogPost">
  <div class="article-meta">
    <a href="/org/2018/10/12/2018-03-13-shiro授权/" class="article-date">
  <time datetime="2018-10-12T09:03:30.000Z" itemprop="datePublished">2018-10-12</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      shiro授权
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="授权"><a href="#授权" class="headerlink" title="授权"></a>授权</h2><p>授权，也叫访问控制，即在应用中控制谁能访问哪些资源（如访问页面/编辑数据/页面操作等）。在授权中需了解的几个关键对象：主体（Subject）、资源（Resource）、权限（Permission）、角色（Role）。</p>
<a id="more"></a>
<p><strong>主体</strong><br>主体，即访问应用的用户，在 Shiro 中使用 Subject 代表该用户。用户只有授权后才允许访问相应的资源</p>
<p><strong>资源</strong><br>在应用中用户可以访问的任何东西，比如访问 JSP 页面、查看/编辑某些数据、访问某个业务方法、打印文本等等都是资源。用户只要授权后才能访问。</p>
<p><strong>权限</strong><br>安全策略中的原子授权单位，通过权限我们可以表示在应用中用户有没有操作某个资源的权力。即权限表示在应用中用户能不能访问某个资源，如： 访问用户列表页面<br>查看/新增/修改/删除用户数据（即很多时候都是 CRUD（增查改删）式权限控制）<br>打印文档等等。。。</p>
<p>如上可以看出，权限代表了用户有没有操作某个资源的权利，即反映在某个资源上的操作允不允许，不反映谁去执行这个操作。所以后续还需要把权限赋予给用户，即定义哪个用户允许在某个资源上做什么操作（权限），Shiro 不会去做这件事情，而是由实现人员提供。</p>
<p>Shiro 支持粗粒度权限（如用户模块的所有权限）和细粒度权限（操作某个用户的权限，即实例级别的），后续部分介绍。</p>
<p><strong>角色</strong><br>角色代表了操作集合，可以理解为权限的集合，一般情况下我们会赋予用户角色而不是权限，即这样用户可以拥有一组权限，赋予权限时比较方便。典型的如：项目经理、技术总监、CTO、开发工程师等都是角色，不同的角色拥有一组不同的权限。</p>
<p><strong>隐式角色</strong>：<br>即直接通过角色来验证用户有没有操作权限，如在应用中 CTO、技术总监、开发工程师可以使用打印机，假设某天不允许开发工程师使用打印机，此时需要从应用中删除相应代码；再如在应用中 CTO、技术总监可以查看用户、查看权限；突然有一天不允许技术总监查看用户、查看权限了，需要在相关代码中把技术总监角色从判断逻辑中删除掉；即粒度是以角色为单位进行访问控制的，粒度较粗；如果进行修改可能造成多处代码修改。</p>
<p><strong>显示角色</strong>：<br>在程序中通过权限控制谁能访问某个资源，角色聚合一组权限集合；这样假设哪个角色不能访问某个资源，只需要从角色代表的权限集合中移除即可；无须修改多处代码；即粒度是以资源/实例为单位的；粒度较细。</p>
<p>请 google 搜索“RBAC”和“RBAC新解”分别了解“基于角色的访问控制”“基于资源的访问控制(Resource-Based Access Control)”。</p>
<h2 id="授权方式"><a href="#授权方式" class="headerlink" title="授权方式"></a>授权方式</h2><p>Shiro 支持三种方式的授权：</p>
<p>编程式：通过写 if/else 授权代码块完成：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Subject subject = SecurityUtils.getSubject();</span><br><span class="line">if(subject.hasRole(“admin”)) &#123;</span><br><span class="line">    //有权限</span><br><span class="line">&#125; else &#123;</span><br><span class="line">    //无权限</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注解式：通过在执行的 Java 方法上放置相应的注解完成：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@RequiresRoles(&quot;admin&quot;)</span><br><span class="line">public void hello() &#123;</span><br><span class="line">    //有权限</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>没有权限将抛出相应的异常；</p>
<p>JSP/GSP 标签：在 JSP/GSP 页面通过相应的标签完成：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;shiro:hasRole name=&quot;admin&quot;&gt;</span><br><span class="line">&lt;!— 有权限 —&gt;</span><br><span class="line">&lt;/shiro:hasRole&gt;</span><br></pre></td></tr></table></figure>
<h2 id="授权-1"><a href="#授权-1" class="headerlink" title="授权"></a>授权</h2><p><strong>基于角色的访问控制（隐式角色）</strong></p>
<p>1、在 ini 配置文件配置用户拥有的角色（shiro-role.ini）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[users]</span><br><span class="line">zhang=123,role1,role2</span><br><span class="line">wang=123,role1</span><br></pre></td></tr></table></figure>
<p>规则即：“用户名=密码,角色1，角色2”，如果需要在应用中判断用户是否有相应角色，就需要在相应的 Realm 中返回角色信息，也就是说 Shiro 不负责维护用户-角色信息，需要应用提供，Shiro 只是提供相应的接口方便验证，后续会介绍如何动态的获取用户角色。</p>
<p>2、测试用例（com.github.zhangkaitao.shiro.chapter3.RoleTest）</p>
<pre><code>@Test
public void testHasRole() {
    login(&quot;classpath:shiro-role.ini&quot;, &quot;zhang&quot;, &quot;123&quot;);
    //判断拥有角色：role1
    Assert.assertTrue(subject().hasRole(&quot;role1&quot;));
    //判断拥有角色：role1 and role2
    Assert.assertTrue(subject().hasAllRoles(Arrays.asList(&quot;role1&quot;, &quot;role2&quot;)));
    //判断拥有角色：role1 and role2 and !role3
    boolean[] result = subject().hasRoles(Arrays.asList(&quot;role1&quot;, &quot;role2&quot;, &quot;role3&quot;));
    Assert.assertEquals(true, result[0]);
    Assert.assertEquals(true, result[1]);
    Assert.assertEquals(false, result[2]);
} 
</code></pre><p>Shiro 提供了 hasRole/hasRole 用于判断用户是否拥有某个角色/某些权限；但是没有提供如 hashAnyRole 用于判断是否有某些权限中的某一个。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Test(expected = UnauthorizedException.class)</span><br><span class="line">public void testCheckRole() &#123;</span><br><span class="line">    login(&quot;classpath:shiro-role.ini&quot;, &quot;zhang&quot;, &quot;123&quot;);</span><br><span class="line">    //断言拥有角色：role1</span><br><span class="line">    subject().checkRole(&quot;role1&quot;);</span><br><span class="line">    //断言拥有角色：role1 and role3 失败抛出异常</span><br><span class="line">    subject().checkRoles(&quot;role1&quot;, &quot;role3&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Shiro 提供的 checkRole/checkRoles 和 hasRole/hasAllRoles 不同的地方是它在判断为假的情况下会抛出 UnauthorizedException 异常。</p>
<p>到此基于角色的访问控制（即隐式角色）就完成了，这种方式的缺点就是如果很多地方进行了角色判断，但是有一天不需要了那么就需要修改相应代码把所有相关的地方进行删除；这就是粗粒度造成的问题。</p>
<p><strong>基于资源的访问控制（显示角色）</strong></p>
<p>1、在 ini 配置文件配置用户拥有的角色及角色-权限关系（shiro-permission.ini）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[users]</span><br><span class="line">zhang=123,role1,role2</span><br><span class="line">wang=123,role1</span><br><span class="line">[roles]</span><br><span class="line">role1=user:create,user:update</span><br><span class="line">role2=user:create,user:delete</span><br></pre></td></tr></table></figure>
<p>规则：“用户名=密码，角色 1，角色 2”“角色=权限 1，权限 2”，即首先根据用户名找到角色，然后根据角色再找到权限；即角色是权限集合；Shiro 同样不进行权限的维护，需要我们通过 Realm 返回相应的权限信息。只需要维护“用户——角色”之间的关系即可</p>
<p>2、测试用例（com.github.zhangkaitao.shiro.chapter3.PermissionTest）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">public void testIsPermitted() &#123;</span><br><span class="line">    login(&quot;classpath:shiro-permission.ini&quot;, &quot;zhang&quot;, &quot;123&quot;);</span><br><span class="line">    //判断拥有权限：user:create</span><br><span class="line">    Assert.assertTrue(subject().isPermitted(&quot;user:create&quot;));</span><br><span class="line">    //判断拥有权限：user:update and user:delete</span><br><span class="line">    Assert.assertTrue(subject().isPermittedAll(&quot;user:update&quot;, &quot;user:delete&quot;));</span><br><span class="line">    //判断没有权限：user:view</span><br><span class="line">    Assert.assertFalse(subject().isPermitted(&quot;user:view&quot;));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Shiro 提供了 isPermitted 和 isPermittedAll 用于判断用户是否拥有某个权限或所有权限，也没有提供如 isPermittedAny 用于判断拥有某一个权限的接口。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@Test(expected = UnauthorizedException.class)</span><br><span class="line">public void testCheckPermission () &#123;</span><br><span class="line">    login(&quot;classpath:shiro-permission.ini&quot;, &quot;zhang&quot;, &quot;123&quot;);</span><br><span class="line">    //断言拥有权限：user:create</span><br><span class="line">    subject().checkPermission(&quot;user:create&quot;);</span><br><span class="line">    //断言拥有权限：user:delete and user:update</span><br><span class="line">    subject().checkPermissions(&quot;user:delete&quot;, &quot;user:update&quot;);</span><br><span class="line">    //断言拥有权限：user:view 失败抛出异常</span><br><span class="line">    subject().checkPermissions(&quot;user:view&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>但是失败的情况下会抛出 UnauthorizedException 异常。</p>
<p>到此基于资源的访问控制（显示角色）就完成了，也可以叫基于权限的访问控制，这种方式的一般规则是“资源标识符：操作”，即是资源级别的粒度；这种方式的好处就是如果要修改基本都是一个资源级别的修改，不会对其他模块代码产生影响，粒度小。但是实现起来可能稍微复杂点，需要维护“用户——角色，角色——权限（资源：操作）”之间的关系。</p>
<h2 id="Permission"><a href="#Permission" class="headerlink" title="Permission"></a>Permission</h2><h3 id="字符串通配符权限"><a href="#字符串通配符权限" class="headerlink" title="字符串通配符权限"></a>字符串通配符权限</h3><p>规则：“资源标识符：操作：对象实例 ID” 即对哪个资源的哪个实例可以进行什么操作。其默认支持通配符权限字符串，“:”表示资源/操作/实例的分割；“,”表示操作的分割；“*”表示任意资源/操作/实例。</p>
<p><strong>1、单个资源单个权限</strong></p>
<p><code>subject().checkPermissions(&quot;system:user:update&quot;);</code></p>
<p>用户拥有资源“system:user”的“update”权限。</p>
<p><strong>2、单个资源多个权限</strong></p>
<p>role41=system:user:update,system:user:delete</p>
<p>然后通过如下代码判断</p>
<p><code>subject().checkPermissions(&quot;system:user:update&quot;, &quot;system:user:delete&quot;);</code></p>
<p>用户拥有资源“system:user”的“update”和“delete”权限。如上可以简写成：</p>
<p>ini 配置（表示角色4拥有 system:user 资源的 update 和 delete 权限）</p>
<p><code>role42=&quot;system:user:update,delete&quot;</code></p>
<p>接着可以通过如下代码判断</p>
<p><code>subject().checkPermissions(&quot;system:user:update,delete&quot;);</code></p>
<p>通过“system:user:update,delete”验证“system:user:update, system:user:delete”是没问题的，但是反过来是规则不成立。</p>
<p><strong>3、单个资源全部权限</strong></p>
<p>ini 配置</p>
<p><code>role51=&quot;system:user:create,update,delete,view&quot;</code></p>
<p>然后通过如下代码判断</p>
<p><code>subject().checkPermissions(&quot;system:user:create,delete,update:view&quot;);</code></p>
<p>用户拥有资源“system:user”的“create”、“update”、“delete”和“view”所有权限。如上可以简写成：</p>
<p>ini 配置文件（表示角色 5 拥有 system:user 的所有权限）</p>
<p><code>role52=system:user:*</code></p>
<p>也可以简写为（推荐上边的写法）：</p>
<p>role53=system:user</p>
<p>然后通过如下代码判断</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">subject().checkPermissions(&quot;system:user:*&quot;);</span><br><span class="line">subject().checkPermissions(&quot;system:user&quot;);</span><br></pre></td></tr></table></figure>
<p>通过“system:user:*”验证“system:user:create,delete,update:view”可以，但是反过来是不成立的。</p>
<p><strong>4、所有资源全部权限</strong></p>
<p>ini 配置</p>
<p><code>role61=*:view</code></p>
<p>然后通过如下代码判断</p>
<p><code>subject().checkPermissions(&quot;user:view&quot;);</code></p>
<p>用户拥有所有资源的“view”所有权限。假设判断的权限是“”system:user:view”，那么需要“role5=<em>:</em>:view”这样写才行</p>
<p><strong>5、实例级别的权限</strong></p>
<ul>
<li><p>单个实例单个权限</p>
<p>ini 配置</p>
<p><code>role71=user:view:1</code></p>
<p>对资源 user 的 1 实例拥有 view 权限。</p>
<p>然后通过如下代码判断</p>
<p><code>subject().checkPermissions(&quot;user:view:1&quot;);</code></p>
<ul>
<li>单个实例多个权限</li>
</ul>
<p>ini 配置</p>
<p><code>role72=&quot;user:update,delete:1&quot;</code></p>
<p>对资源 user 的 1 实例拥有 update、delete 权限。</p>
<p>然后通过如下代码判断</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">subject().checkPermissions(&quot;user:delete,update:1&quot;);</span><br><span class="line">subject().checkPermissions(&quot;user:update:1&quot;, &quot;user:delete:1&quot;);</span><br></pre></td></tr></table></figure>
<ul>
<li><p>单个实例所有权限</p>
<p>​</p>
</li>
</ul>
<p>ini 配置</p>
<p><code>role73=user:*:1</code></p>
<p>对资源 user 的 1 实例拥有所有权限。</p>
<p>然后通过如下代码判断</p>
<p><code>subject().checkPermissions(&quot;user:update:1&quot;, &quot;user:delete:1&quot;, &quot;user:view:1&quot;);</code></p>
<ul>
<li>所有实例单个权限</li>
</ul>
<p>ini 配置</p>
<p><code>role74=user:auth:*</code></p>
<p>对资源 user 的 1 实例拥有所有权限。</p>
<p>然后通过如下代码判断</p>
<p><code>subject().checkPermissions(&quot;user:auth:1&quot;, &quot;user:auth:2&quot;);</code></p>
<ul>
<li><p>所有实例所有权限</p>
<p>ini 配置</p>
<p><code>role75=user:*:*</code></p>
<p>对资源 user 的 1 实例拥有所有权限。</p>
<p>然后通过如下代码判断</p>
<p><code>subject().checkPermissions(&quot;user:view:1&quot;, &quot;user:auth:2&quot;);</code></p>
</li>
</ul>
</li>
</ul>
<p><strong>6、Shiro 对权限字符串缺失部分的处理</strong></p>
<p>如“user:view”等价于“<code>user:view:*</code>”；而“organization”等价于“<code>organization:*</code>”或者“<code>organization:*:*</code>”。可以这么理解，这种方式实现了前缀匹配。</p>
<p>另外如“<code>user:*</code>”可以匹配如“<code>user:delete</code>”、“<code>user:delete</code>”可以匹配如“<code>user:delete:1</code>”、“<code>user:*:1</code>”可以匹配如“user:view:1”、“user”可以匹配“<code>user:view</code>”或“<code>user:view:1</code>”等。即<code>*</code>可以匹配所有，不加<code>*</code>可以进行前缀匹配；但是如“<code>*:view</code>”不能匹配“<code>system:user:view</code>”，需要使用“<code>*:*:view</code>”，即后缀匹配必须指定前缀（多个冒号就需要多个<code>*</code>来匹配）。</p>
<p><strong>7、WildcardPermission</strong></p>
<p>如下两种方式是等价的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">subject().checkPermission(&quot;menu:view:1&quot;);</span><br><span class="line">subject().checkPermission(new WildcardPermission(&quot;menu:view:1&quot;));</span><br></pre></td></tr></table></figure>
<p>因此没什么必要的话使用字符串更方便。</p>
<p><strong>8、性能问题</strong></p>
<p>通配符匹配方式比字符串相等匹配来说是更复杂的，因此需要花费更长时间，但是一般系统的权限不会太多，且可以配合缓存来提供其性能，如果这样性能还达不到要求我们可以实现位操作算法实现性能更好的权限匹配。另外实例级别的权限验证如果数据量太大也不建议使用，可能造成查询权限及匹配变慢。可以考虑比如在sql查询时加上权限字符串之类的方式在查询时就完成了权限匹配。</p>
<h2 id="授权流程"><a href="#授权流程" class="headerlink" title="授权流程"></a>授权流程</h2><p><img src="http://p1aoqp63y.bkt.clouddn.com/6.png" alt="2"></p>
<p>流程如下：</p>
<ol>
<li>首先调用 <code>Subject.isPermitted*/hasRole*</code>接口，其会委托给 SecurityManager，而 SecurityManager 接着会委托给 Authorizer；</li>
<li>Authorizer 是真正的授权者，如果我们调用如 isPermitted(“user:view”)，其首先会通过 PermissionResolver 把字符串转换成相应的 Permission 实例；</li>
<li>在进行授权之前，其会调用相应的 Realm 获取 Subject 相应的角色/权限用于匹配传入的角色/权限；</li>
<li>Authorizer 会判断 Realm 的角色/权限是否和传入的匹配，如果有多个 Realm，会委托给 ModularRealmAuthorizer 进行循环判断，如果匹配如 <code>isPermitted*/hasRole*</code> 会返回 true，否则返回 false 表示授权失败。</li>
</ol>
<p>ModularRealmAuthorizer 进行多 Realm 匹配流程：</p>
<ul>
<li>首先检查相应的 Realm 是否实现了实现了 Authorizer；</li>
<li>如果实现了 Authorizer，那么接着调用其相应的 <code>isPermitted*/hasRole*</code> 接口进行匹配；</li>
<li>如果有一个 Realm 匹配那么将返回 true，否则返回 false。</li>
</ul>
<p>如果 Realm 进行授权的话，应该继承 AuthorizingRealm，其流程是：</p>
<ul>
<li>如果调用 <code>hasRole*</code>，则直接获取 AuthorizationInfo.getRoles() 与传入的角色比较即可；首先如果调用如 isPermitted(“user:view”)，首先通过 PermissionResolver 将权限字符串转换成相应的 Permission 实例，默认使用 WildcardPermissionResolver，即转换为通配符的 WildcardPermission；</li>
<li>通过 AuthorizationInfo.getObjectPermissions() 得到 Permission 实例集合；通过 AuthorizationInfo.getStringPermissions() 得到字符串集合并通过 PermissionResolver 解析为 Permission 实例；然后获取用户的角色，并通过 RolePermissionResolver 解析角色对应的权限集合（默认没有实现，可以自己提供）；</li>
<li>接着调用 Permission.implies(Permission p) 逐个与传入的权限比较，如果有匹配的则返回 true，否则 false。</li>
</ul>
<h2 id="Authorizer、PermissionResolver及RolePermissionResolver"><a href="#Authorizer、PermissionResolver及RolePermissionResolver" class="headerlink" title="Authorizer、PermissionResolver及RolePermissionResolver"></a>Authorizer、PermissionResolver及RolePermissionResolver</h2><p>Authorizer 的职责是进行授权（访问控制），是 Shiro API 中授权核心的入口点，其提供了相应的角色/权限判断接口，具体请参考其 Javadoc。SecurityManager 继承了 Authorizer 接口，且提供了 ModularRealmAuthorizer 用于多 Realm 时的授权匹配。PermissionResolver 用于解析权限字符串到 Permission 实例，而 RolePermissionResolver 用于根据角色解析相应的权限集合。</p>
<p>我们可以通过如下 ini 配置更改 Authorizer 实现：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">authorizer=org.apache.shiro.authz.ModularRealmAuthorizer</span><br><span class="line">securityManager.authorizer=$authorizer</span><br></pre></td></tr></table></figure>
<p>对于 ModularRealmAuthorizer，相应的 AuthorizingSecurityManager 会在初始化完成后自动将相应的 realm 设置进去，我们也可以通过调用其 setRealms() 方法进行设置。对于实现自己的 authorizer 可以参考 ModularRealmAuthorizer 实现即可，在此就不提供示例了。</p>
<p>设置 ModularRealmAuthorizer 的 permissionResolver，其会自动设置到相应的 Realm 上（其实现了 PermissionResolverAware 接口），如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">permissionResolver=org.apache.shiro.authz.permission.WildcardPermissionResolver</span><br><span class="line">authorizer.permissionResolver=$permissionResolver</span><br></pre></td></tr></table></figure>
<p>设置 ModularRealmAuthorizer 的 rolePermissionResolver，其会自动设置到相应的 Realm 上（其实现了 RolePermissionResolverAware 接口），如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">rolePermissionResolver=com.github.zhangkaitao.shiro.chapter3.permission.MyRolePermissionResolver</span><br><span class="line">authorizer.rolePermissionResolver=$rolePermissionResolver</span><br></pre></td></tr></table></figure>
<p><strong>示例</strong></p>
<p><strong>1、ini 配置（shiro-authorizer.ini）</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">[main]</span><br><span class="line">\#自定义authorizer</span><br><span class="line">authorizer=org.apache.shiro.authz.ModularRealmAuthorizer</span><br><span class="line">\#自定义permissionResolver</span><br><span class="line">\#permissionResolver=org.apache.shiro.authz.permission.WildcardPermissionResolver</span><br><span class="line">permissionResolver=com.github.zhangkaitao.shiro.chapter3.permission.BitAndWildPermissionResolver</span><br><span class="line">authorizer.permissionResolver=$permissionResolver</span><br><span class="line">\#自定义rolePermissionResolver</span><br><span class="line">rolePermissionResolver=com.github.zhangkaitao.shiro.chapter3.permission.MyRolePermissionResolver</span><br><span class="line">authorizer.rolePermissionResolver=$rolePermissionResolver</span><br><span class="line">securityManager.authorizer=$authorizer</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">\#自定义realm 一定要放在securityManager.authorizer赋值之后（因为调用setRealms会将realms设置给authorizer，并给各个Realm设置permissionResolver和rolePermissionResolver）</span><br><span class="line">realm=com.github.zhangkaitao.shiro.chapter3.realm.MyRealm</span><br><span class="line">securityManager.realms=$realm</span><br></pre></td></tr></table></figure>
<p>设置 securityManager 的 realms 一定要放到最后，因为在调用 SecurityManager.setRealms 时会将 realms 设置给 authorizer，并为各个 Realm 设置 permissionResolver 和 rolePermissionResolver。另外，不能使用 IniSecurityManagerFactory 创建的 IniRealm，因为其初始化顺序的问题可能造成后续的初始化 Permission 造成影响</p>
<p><strong>2、定义 BitAndWildPermissionResolver 及 BitPermission</strong></p>
<p>BitPermission 用于实现位移方式的权限，如规则是：</p>
<p>权限字符串格式：+ 资源字符串 + 权限位 + 实例 ID；以 + 开头中间通过 + 分割；权限：0 表示所有权限；1 新增（二进制：0001）、2 修改（二进制：0010）、4 删除（二进制：0100）、8 查看（二进制：1000）；如 +user+10 表示对资源 user 拥有修改 / 查看权限。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">public class BitPermission implements Permission &#123;</span><br><span class="line">    private String resourceIdentify;</span><br><span class="line">    private int permissionBit;</span><br><span class="line">    private String instanceId;</span><br><span class="line">    public BitPermission(String permissionString) &#123;</span><br><span class="line">        String[] array = permissionString.split(&quot;\\+&quot;);</span><br><span class="line">        if(array.length &gt; 1) &#123;</span><br><span class="line">            resourceIdentify = array[1];</span><br><span class="line">        &#125;</span><br><span class="line">        if(StringUtils.isEmpty(resourceIdentify)) &#123;</span><br><span class="line">            resourceIdentify = &quot;*&quot;;</span><br><span class="line">        &#125;</span><br><span class="line">        if(array.length &gt; 2) &#123;</span><br><span class="line">            permissionBit = Integer.valueOf(array[2]);</span><br><span class="line">        &#125;</span><br><span class="line">        if(array.length &gt; 3) &#123;</span><br><span class="line">            instanceId = array[3];</span><br><span class="line">        &#125;</span><br><span class="line">        if(StringUtils.isEmpty(instanceId)) &#123;</span><br><span class="line">            instanceId = &quot;*&quot;;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    public boolean implies(Permission p) &#123;</span><br><span class="line">        if(!(p instanceof BitPermission)) &#123;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line">        BitPermission other = (BitPermission) p;</span><br><span class="line">        if(!(&quot;*&quot;.equals(this.resourceIdentify) || this.resourceIdentify.equals(other.resourceIdentify))) &#123;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line">        if(!(this.permissionBit ==0 || (this.permissionBit &amp; other.permissionBit) != 0)) &#123;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line">        if(!(&quot;*&quot;.equals(this.instanceId) || this.instanceId.equals(other.instanceId))) &#123;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line">        return true;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Permission 接口提供了 boolean implies(Permission p) 方法用于判断权限匹配的；</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public class BitAndWildPermissionResolver implements PermissionResolver &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public Permission resolvePermission(String permissionString) &#123;</span><br><span class="line">        if(permissionString.startsWith(&quot;+&quot;)) &#123;</span><br><span class="line">            return new BitPermission(permissionString);</span><br><span class="line">        &#125;</span><br><span class="line">        return new WildcardPermission(permissionString);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>BitAndWildPermissionResolver 实现了 PermissionResolver 接口，并根据权限字符串是否以 “+” 开头来解析权限字符串为 BitPermission 或 WildcardPermission。</p>
<p><strong>3、定义 MyRolePermissionResolver</strong></p>
<p>RolePermissionResolver 用于根据角色字符串来解析得到权限集合。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public class MyRolePermissionResolver implements RolePermissionResolver &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public Collection&lt;Permission&gt; resolvePermissionsInRole(String roleString) &#123;</span><br><span class="line">        if(&quot;role1&quot;.equals(roleString)) &#123;</span><br><span class="line">            return Arrays.asList((Permission)new WildcardPermission(&quot;menu:*&quot;));</span><br><span class="line">        &#125;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此处的实现很简单，如果用户拥有 role1，那么就返回一个 “<code>menu:*</code>” 的权限。</p>
<p><strong>4、自定义 Realm</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">public class MyRealm extends AuthorizingRealm &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) &#123;</span><br><span class="line">        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();</span><br><span class="line">        authorizationInfo.addRole(&quot;role1&quot;);</span><br><span class="line">        authorizationInfo.addRole(&quot;role2&quot;);</span><br><span class="line">        authorizationInfo.addObjectPermission(new BitPermission(&quot;+user1+10&quot;));</span><br><span class="line">        authorizationInfo.addObjectPermission(new WildcardPermission(&quot;user1:*&quot;));</span><br><span class="line">        authorizationInfo.addStringPermission(&quot;+user2+10&quot;);</span><br><span class="line">        authorizationInfo.addStringPermission(&quot;user2:*&quot;);</span><br><span class="line">        return authorizationInfo;</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException &#123;</span><br><span class="line">        //和com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1. getAuthenticationInfo代码一样，省略</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时我们继承 AuthorizingRealm 而不是实现 Realm 接口；推荐使用 AuthorizingRealm，因为： AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)：表示获取身份验证信息；AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)：表示根据用户身份获取授权信息。这种方式的好处是当只需要身份验证时只需要获取身份验证信息而不需要获取授权信息。对于 AuthenticationInfo 和 AuthorizationInfo 请参考其 Javadoc 获取相关接口信息。</p>
<p>另外我们可以使用 JdbcRealm，需要做的操作如下：</p>
<ol>
<li>执行 sql/ shiro-init-data.sql 插入相关的权限数据；</li>
<li>使用 shiro-jdbc-authorizer.ini 配置文件，需要设置 jdbcRealm.permissionsLookupEnabled 为 true 来开启权限查询。</li>
</ol>
<p>此次还要注意就是不能把我们自定义的如 “+user1+10” 配置到 INI 配置文件，即使有 IniRealm 完成，因为 IniRealm 在 new 完成后就会解析这些权限字符串，默认使用了WildcardPermissionResolver 完成，即此处是一个设计权限，如果采用生命周期（如使用初始化方法）的方式进行加载就可以解决我们自定义 permissionResolver 的问题。</p>
<p><strong>5、测试用例</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public class AuthorizerTest extends BaseTest &#123;</span><br><span class="line">    @Test</span><br><span class="line">    public void testIsPermitted() &#123;</span><br><span class="line">        login(&quot;classpath:shiro-authorizer.ini&quot;, &quot;zhang&quot;, &quot;123&quot;);</span><br><span class="line">        //判断拥有权限：user:create</span><br><span class="line">        Assert.assertTrue(subject().isPermitted(&quot;user1:update&quot;));</span><br><span class="line">        Assert.assertTrue(subject().isPermitted(&quot;user2:update&quot;));</span><br><span class="line">        //通过二进制位的方式表示权限</span><br><span class="line">        Assert.assertTrue(subject().isPermitted(&quot;+user1+2&quot;));//新增权限</span><br><span class="line">        Assert.assertTrue(subject().isPermitted(&quot;+user1+8&quot;));//查看权限</span><br><span class="line">        Assert.assertTrue(subject().isPermitted(&quot;+user2+10&quot;));//新增及查看</span><br><span class="line">        Assert.assertFalse(subject().isPermitted(&quot;+user1+4&quot;));//没有删除权限</span><br><span class="line">        Assert.assertTrue(subject().isPermitted(&quot;menu:view&quot;));//通过MyRolePermissionResolver解析得到的权限</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过如上步骤可以实现自定义权限验证了。另外因为不支持 hasAnyRole/isPermittedAny 这种方式的授权</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2018/10/12/2018-03-13-shiro授权/" data-id="cjoztxu2i000j1wijkml4f384" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/org/tags/shiro/">shiro</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/org/2018/10/12/2018-03-01-shiro JSP标签/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          Shiro JSP标签
        
      </div>
    </a>
  
  
    <a href="/org/2018/10/12/2018-03-13-shiro简介/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">shiro简介</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/SVN/">SVN</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/Spring-secrity/">Spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hexo/">hexo</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hibenrate/">hibenrate</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jekyll/">jekyll</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jenkins/">jenkins</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/redis/">redis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/shiro/">shiro</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spingMVC/">spingMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring-cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-secrity/">spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springMVC/">springMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springboot/">springboot</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/生活/">生活</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/org/tags/SVN/" style="font-size: 12px;">SVN</a> <a href="/org/tags/Spring-secrity/" style="font-size: 10px;">Spring-secrity</a> <a href="/org/tags/hexo/" style="font-size: 10px;">hexo</a> <a href="/org/tags/hibenrate/" style="font-size: 10px;">hibenrate</a> <a href="/org/tags/jekyll/" style="font-size: 10px;">jekyll</a> <a href="/org/tags/jenkins/" style="font-size: 10px;">jenkins</a> <a href="/org/tags/redis/" style="font-size: 16px;">redis</a> <a href="/org/tags/shiro/" style="font-size: 18px;">shiro</a> <a href="/org/tags/spingMVC/" style="font-size: 10px;">spingMVC</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring cloud</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring-cloud</a> <a href="/org/tags/spring-secrity/" style="font-size: 12px;">spring-secrity</a> <a href="/org/tags/springMVC/" style="font-size: 14px;">springMVC</a> <a href="/org/tags/springboot/" style="font-size: 20px;">springboot</a> <a href="/org/tags/生活/" style="font-size: 10px;">生活</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/11/">November 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/10/">October 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/org/2018/11/27/redis07-zookeeper-kafka集群部署以及如何使用简单介绍/">redis07-zookeeper+kafka集群部署以及如何使用简单介绍</a>
          </li>
        
          <li>
            <a href="/org/2018/11/13/redis06-cluster实现高可用性/">redis06-cluster实现高可用性</a>
          </li>
        
          <li>
            <a href="/org/2018/11/12/redis05-在项目中搭建读写分-高可用-多master的redis-cluster集群/">redis05-在项目中搭建读写分+高可用+多master的redis cluster集群</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/在项目中用经典的三节点方式部署哨兵集群-笔记/">在项目中用经典的三节点方式部署哨兵集群-笔记</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/redis哨兵的多个核心底层原理-笔记/">redis哨兵的多个核心底层原理-笔记</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/org/" class="mobile-nav-link">Home</a>
  
    <a href="/org/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>


  <link rel="stylesheet" href="/org/fancybox/jquery.fancybox.css">
  <script src="/org/fancybox/jquery.fancybox.pack.js"></script>


<script src="/org/js/script.js"></script>



  </div>
</body>
</html>